﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Samples.ServiceHosting.StorageClient;
using Microsoft.ServiceHosting.ServiceRuntime;
using System.Collections.Specialized;
using System.IO;
using UlyssesAgenda.GameEngine;

namespace UlyssesAgenda.Repositories.GameObjects
{
    public class GameObjectRepository : CloudStorageRepositoryBase
    {      
        public GameObjectRepository(StorageAccountInfo blob, StorageAccountInfo queue, StorageAccountInfo table) : base(blob, queue, table)
        {
            InitBlobContainer(RoleManager.GetConfigurationSetting("GameObjectsContainer"));
        }

        public GameObjectInfo[] GetGameObjects()
        {
            IEnumerable<object> blobs = blobContainer.ListBlobs(string.Empty, false);
            List<GameObjectInfo> regionFiles = new List<GameObjectInfo>();
            foreach (object blobObject in blobs)
            {
                BlobProperties props = blobObject as BlobProperties;
                if (props != null)
                {
                    BlobProperties blobProps = blobContainer.GetBlobProperties(props.Name);
                    NameValueCollection nvc = blobProps.Metadata;
                    regionFiles.Add(new GameObjectInfo()
                    {
                        Url = props.Uri.ToString(),
                        CanonicalName = blobProps.Name,
                        LastSave = DateTime.Parse(nvc["LastSave"])
                    });
                }
            }
            return regionFiles.ToArray();
        }

        public GameObjectInfo GetGameObject(string canonicalName)
        {
            BlobContents contents = new BlobContents(new MemoryStream());
            BlobProperties props = blobContainer.GetBlob(canonicalName, contents, false);
            NameValueCollection metadata = props.Metadata;
            GameObjectInfo info = new GameObjectInfo()
            {
                CanonicalName = canonicalName,
                LastSave = DateTime.Parse(metadata["LastSave"]),
                Url = props.Uri.ToString(),
                State = Engine.GetState(canonicalName)
            };

            return info;
                 
        }

        public void CreateGameObject(string canonicalName)
        {                        
            Dictionary<string, string> foo = new Dictionary<string, string>();
            foo.Add("Sample", "Test");
            Engine.SaveState(canonicalName, foo);

        }
    }
}
